/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package controllers.managecontrollers;

import classes.Breadcrumbs;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import models.Category;
import models.Course;
import models.Employee;
import dao.CategoryDao;
import dao.CourseDao;
import dao.EmployeeDao;
import classes.HibernateUtil;

/**
 *  This servlet manages the add, edit and remove of a course.
 * Redirects to the right pages.
 * 
 * @author Achie
 */
public class ManageCourseController extends HttpServlet {

    /*
     * This do get method checks if a course has to be removed,edited or added.
     * Sets attributes depending on the action.
     * Redirects to the right page
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        //------------------------------------------------
        //Setup page
        //------------------------------------------------
        if (request.getParameter("catid")!= null){
            HibernateUtil hu = new HibernateUtil();            
            Course course = new Course();            
            CategoryDao catd = new CategoryDao(hu.openSession());
            List<Category> categories = catd.findAll();
            Category categor = new Category();
            categor.setId(Long.parseLong(request.getParameter("catid")));
            request.setAttribute("catid", categor.getId());
            request.setAttribute("categories", categories);
            EmployeeDao dd = new EmployeeDao(hu.openSession());
            List<Employee> employees = dd.findAll();
            request.setAttribute("employees", employees);
            
            // Breadcrumbs
            Breadcrumbs[] breadcrumbs = {
                new Breadcrumbs("Index", "Home"),
                new Breadcrumbs("Category?edit", "Manage categories and courses"),
                new Breadcrumbs("ManageCourse/form?catid", "Add course")
            };
            request.setAttribute("breadcrumbs", breadcrumbs);
            
            RequestDispatcher dispatcher = request.getRequestDispatcher("/jsp/add_edit_courses.jsp");
            dispatcher.forward(request, response);
            
            
            
        }else if (request.getParameter("idedit") != null) { //modify, course page

            long course_id = Long.parseLong(request.getParameter("idedit"));
            //grab selected catalog object
            HibernateUtil hu = new HibernateUtil();
            CourseDao cd = new CourseDao(hu.openSession());
            Course course = cd.get(course_id);
            CategoryDao catd = new CategoryDao(hu.openSession());
            List<Category> categories = catd.findAll();
            request.setAttribute("categories", categories);
            EmployeeDao dd = new EmployeeDao(hu.openSession());
            List<Employee> employees = dd.findAll();
            request.setAttribute("employees", employees);
            request.setAttribute("coursetoedit", course);
            
            // Breadcrumbs
            Breadcrumbs[] breadcrumbs = {
                new Breadcrumbs("Index", "Home"),
                new Breadcrumbs("Category?edit", "Manage categories and courses"),
                new Breadcrumbs("ManageCourse/form?editid", "Edit course")
            };
            request.setAttribute("breadcrumbs", breadcrumbs);
            
            RequestDispatcher dispatcher = request.getRequestDispatcher("/jsp/add_edit_courses.jsp");
            dispatcher.forward(request, response);


        } else if (request.getParameter("idremove") != null) {
            long id = Long.parseLong(request.getParameter("idremove"));
            HibernateUtil hu = new HibernateUtil();

            CourseDao coursedao = new CourseDao(hu.openSession());
            Course cu = coursedao.get(id); //get course
            coursedao.delete(cu); //remove it
            response.sendRedirect("../Category?edit");
        } else { //add new course page            
            HibernateUtil hu = new HibernateUtil();
            //-----------------------------------------------------------------
            //Prepare teachers and categories
            //-----------------------------------------------------------------
            CategoryDao cd = new CategoryDao(hu.openSession());
            EmployeeDao dd = new EmployeeDao(hu.openSession());
            List<Employee> employees = dd.findAll();
            List<Category> categories = cd.findAll();
            request.setAttribute("employees", employees);
            request.setAttribute("categories", categories); 

            //Redirect
            request.getRequestDispatcher("/jsp/add_edit_courses.jsp").forward(request, response);
            //RequestDispatcher dispatcher = request.getRequestDispatcher("/jsp/add_edit_courses.jsp");
            //dispatcher.forward(request, response);

        }


    }

    /*
     * this do post method saves or edits the courses.
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //----------------------------------------------------------
        //Get values from from, regardless add/modify
        //----------------------------------------------------------
        long course_id = System.nanoTime();
        String name = request.getParameter("name");
        String description = request.getParameter("description");
        double price = Double.parseDouble(request.getParameter("price").replace(",", "."));
        String currency = request.getParameter("currency");
        long cat_id = Long.parseLong(request.getParameter("category"));
        
        //----------------------------------------------------------
        //Get the chosen category object
        //----------------------------------------------------------
        HibernateUtil hu = new HibernateUtil();
        CategoryDao cd = new CategoryDao(hu.openSession());
        Category cat = cd.get(cat_id);        

        //----------------------------------------------------------
        //Is it an add or modification of the course?
        //----------------------------------------------------------

        if (request.getParameter("formoption").equals("add")) { //add new course
            Set<Employee> employeeList = getSelectedEmployees(request); //get selected employees

            //Create new course object
            Course course = new Course(course_id, name, description, price, currency, cat);
            course.setTeacher(employeeList);//set the teachers
            
            //Save in the database
            CourseDao ccd = new CourseDao(hu.openSession());
            ccd.save(course);
        } else if (request.getParameter("formoption").equals("edit")) { //
            long idcourse = Long.parseLong(request.getParameter("idcourse"));
            CourseDao coursedata = new CourseDao(hu.openSession());
            
            //get the object
            HttpSession ses = request.getSession();
            
            Set<Employee> employees;
            if(ses.getAttribute("userrole").equals("Teacher")) {
                employees = coursedata.get(idcourse).getTeacher();
            } else {
                employees = getSelectedEmployees(request); //update nieuwe lijst
            }
        
            Course co = coursedata.get(idcourse);
            co.setName(name);
            co.setDescription(description);
            co.setPrice(price);
            co.setCurrency(currency);
            co.setCategory(cat);
            co.setTeacher(employees);
            coursedata.update(co); //update course
        }      
            if(request.getParameter("catid")!=null){
        
            }else{        
        response.sendRedirect("Category?edit");
                //response.sendRedirect("ManageCourseView");
            }

    }

    //method that returns a list of teachers
    public Set<Employee> getSelectedEmployees(HttpServletRequest request) { //Get the selected teachers
        HibernateUtil hu = new HibernateUtil();
        EmployeeDao ed = new EmployeeDao(hu.openSession());
        String[] selected_teacher_id = request.getParameterValues("selectedteachers"); //selected teachers id
        Set<Employee> employeeList = new HashSet<Employee>(); //list that holds the selected teachers
        for (int i = 0; i < selected_teacher_id.length; i++) { //Get the teacher object via the id and add to list
            long tempid = Long.parseLong(selected_teacher_id[i]);
            Employee emp = ed.get(tempid);
            employeeList.add(emp);//add this current teacher to the list
        }
        return employeeList;
    }
    
}
